package cn.com.pc.content.config;

import cn.com.pc.content.domain.Site;
import cn.com.pc.content.service.SiteOperatorService;
import cn.com.pc.rbac.client.RbacContext;
import cn.com.pc.rbac.client.model.Operator;
import cn.com.pc.rbac.client.model.Permission;
import cn.com.pc.rbac.client.model.Role;
import lombok.RequiredArgsConstructor;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Objects;

@RequiredArgsConstructor
public class SiteRbacContext implements RbacContext {

    private final RbacContext target;
    private final SiteOperatorService siteOperatorService;


    // 用 @Rbac("siteOperator") 标注方式使用， 提取站点 判断数据权限
    public boolean getSiteOperator() {

        HttpServletRequest req = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();

        Long accountId = (Long) req.getAttribute("aaa-identity-id");

        Site site = (Site) req.getAttribute("site");

        return siteOperatorService.isSiteOperator(site, accountId) && hasRole(new String[]{"operator"}) || hasRole(new String[]{"admin"});
    }


    // Proxy to target
    @Override
    public Operator operator() {
        return target.operator();
    }

    @Override
    public List<Role> roles() {
        return target.roles();
    }

    @Override
    public List<Permission> permissions() {
        return target.permissions();
    }
    

}
